<template>
  <template v-if="isAuditMode==true">
    <view class="ss-flex-row ss-row-center ss-m-t-80">改功能暂未开发</view>
  </template>

  <template v-else>
	<assNavbar title="日常分享"></assNavbar>
    <view
      class="content"
      :style="{ minHeight: state.minHeight + 'px' }"
    >
      <view
        class="describe"
        :style="{ borderColor: theme.main_color }"
      >
        <textarea
          placeholder="请输入作品描述"
          :disable-default-padding="true"
          :maxlength="80"
          v-model="state.title"
        ></textarea>
        <view class="describe-number"><text>{{ state.title.length }}</text>/80字</view>
      </view>
      <!-- <view class="carry ss-flex">
				<view class="carry-item" :style="{borderColor:theme.main_color}" @click="addMain">#主题</view>
				<view class="carry-item" :style="{borderColor:theme.main_color}" @click="addFriend">@朋友</view>
			</view> -->
      <view class="video-box ss-flex justify-between align-center">
        <view class="video ss-flex flex-column justify-center align-center">
          <!-- 
					autoplay 是否自动播放
					loop 是否循环播放
					enable-progress-gesture 是否开启控制进度的手势
					page-gesture 在非全屏模式下，是否开启亮度与音量调节手势
					controls 是否显示默认播放控件
					http-cache 是否对 http、https 视频源开启本地缓存。缓存策略:开启了此开关的视频源，
							   在视频播放时会在本地保存缓存文件，如果本地缓存池已超过100M，在进行缓存前会清空之前的缓存（不适用于m3u8等流媒体协议）
					show-loading 是否显示loading控件
					show-fullscreen-btn 是否显示全屏按钮
					show-center-play-btn 是否显示视频中间的播放按钮
					object-fit 当视频大小与 video 容器大小不一致时，视频的表现形式。contain：包含，fill：填充，cover：覆盖
					 -->
          <video
            v-if="state.videoDetails"
            :muted="true"
            id="video"
            :src="state.videoDetails.path"
            :autoplay="true"
            :loop="false"
            :enable-progress-gesture="false"
            :page-gesture="false"
            :controls="false"
            :http-cache="true"
            :show-loading="false"
            :show-fullscreen-btn="false"
            :show-center-play-btn="false"
            object-fit="fill"
            :style="state.videoBox"
            @loadeddata="loadeddata"
          ></video>
          <view class="video-duration">{{ state.videoDetails?.duration || '0' }} ″</view>
        </view>
        <view
          class="cover ss-flex flex-column justify-center align-center"
          @click="changeCover"
        >
          <image
            class="cover-image"
            v-if="state.videoDetails"
            :src="state.videoDetails.thumbTempFilePath"
            mode="aspectFill"
            :style="[{ width: state.videoWidth + 'px', height: state.videoHeight + 'px' }]"
          >
          </image>
          <view class="cover-text">封面</view>
        </view>
      </view>

      <view class="settings">
        <view
          class="settings-item ss-flex justify-between align-center"
          @click="state.cart_show = true"
        >
          <view class="ss-flex">
            <uni-icons
              type="cart"
              size="28"
              color="#000000"
            ></uni-icons>
            <view
              class="settings-text ss-line-1"
              v-if="state.goods"
            >{{ state.goods.title }}</view>
            <view
              class="settings-text ss-line-1"
              v-if="state.shop"
            >{{ state.shop.title }}</view>
            <view
              class="settings-text"
              v-if="!state.shop && !state.goods"
            >推荐带货</view>
          </view>
          <view class="settings-item-right">
            <uni-icons
              type="forward"
              size="26"
              color="#000000"
            ></uni-icons>
          </view>
        </view>
        <!-- <view
		    class="settings-item ss-flex justify-between align-center"
		    @click="state.settings_show = true"
		  >
		    <view class="ss-flex">
		      <uni-icons type="gear" size="28" color="#000000"></uni-icons>
		      <view class="settings-text">更多设置</view>
		    </view>
		
		    <view class="settings-item-right">
		      <uni-icons type="forward" size="26" color="#000000"></uni-icons>
		    </view>
		  </view> -->
      </view>

      <!-- 发布 -->
      <view class="publish ss-flex justify-center align-center ss-safe-bottom">
        <view
          class="publish-btn ss-flex justify-center align-center"
          @click="submit"
          :style="{ background: theme.main_color }"
        >
          <view class="fabu ss-flex justify-center align-center">
            <uni-icons
              type="arrow-up"
              size="20"
              :color="theme.main_color"
            ></uni-icons>
          </view>
          <view class="publish-btn-text">发布</view>
        </view>
      </view>
    </view>
  </template>

  <!-- <su-popup
    type="bottom"
    @change="changeSettingsPop"
    :show="state.settings_show"
    backgroundColor="#fff"
    maskBackgroundColor="rgba(0, 0, 0, 0.8)"
    :round="30"
  >
    <view class="settings-box">
      <view class="settings-title">更多设置</view>
      <view class="settings-items ss-flex justify-between align-center border-b-f3">
        <view class="settings-left">允许下载</view>
        <view class="settings-right">
          <switch
            :checked="state.download"
            :color="theme.main_color"
            style="transform: scale(0.7)"
          />
        </view>
      </view>
      <view
        class="settings-items ss-flex justify-between align-center border-b-f3"
        @click="changePowerType('transpond')"
      >
        <view class="settings-left">转发权限</view>
        <view class="settings-right ss-flex justify-center align-center">
          <view class="right-text">
            <text v-show="state.transpond === 'my'">仅自己</text>
            <text v-show="state.transpond === 'friends'">仅互关好友</text>
            <text v-show="state.transpond === 'all'">所有人</text>
          </view>
          <uni-icons type="right" size="25" color="#BCBCBC"></uni-icons>
        </view>
      </view>
      <view
        class="settings-items ss-flex justify-between align-center"
        @click="changePowerType('comment')"
      >
        <view class="settings-left">评论权限</view>
        <view class="settings-right ss-flex justify-center align-center">
          <view class="right-text">
            <text v-show="state.comment === 'my'">仅自己</text>
            <text v-show="state.comment === 'friends'">仅互关好友</text>
            <text v-show="state.comment === 'all'">所有人</text>
          </view>
          <uni-icons type="right" size="25" color="#BCBCBC"></uni-icons>
        </view>
      </view>
      <view class="ss-flex justify-center ss-m-t-40" @click="state.settings_show = false">
        <uni-icons type="down" size="25" color="#BCBCBC"></uni-icons>
      </view>
    </view>
  </su-popup> -->

  <su-popup
    type="bottom"
    @change="changeCartPop"
    :show="state.cart_show"
    backgroundColor="#fff"
    maskBackgroundColor="rgba(0, 0, 0, 0.8)"
    :round="30"
  >
    <view class="cart-box">
      <view
        v-if="platform=='xyh'"
        class="cart-box-item ss-flex align-center border-b-f3"
        @click="
          state.cart_show = false;
          sheep.$router.go('/pages/release/store_list', {
            backPage: '/association/pages/publishVideo',
          });
        "
      >
        <image
          class="cart-image"
          src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250416/5fc3d36866047ed562343c1f7f36dfad.png"
        ></image>
        <view class="cart-name">添加本地生活门店</view>
      </view>

      <view
        class="cart-box-item ss-flex align-center"
        @click="
          state.cart_show = false;
          sheep.$router.go('/pages/release/product_list', {
            backPage: '/association/pages/publishVideo',
          });
        "
      >
        <image
          class="cart-image"
          src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250416/0742001d0f32272e99c5914f5a12a98b.png"
        ></image>
        <view class="cart-name">添加商城商品</view>
      </view>
      <view
        class="ss-flex justify-center ss-m-t-80"
        @click="state.cart_show = false"
      >
        <uni-icons
          type="down"
          size="25"
          color="#BCBCBC"
        ></uni-icons>
      </view>
    </view>
  </su-popup>

  <su-popup
    type="bottom"
    @change="changePowerPop"
    :show="state.power_show"
    backgroundColor="#fff"
    maskBackgroundColor="rgba(0, 0, 0, 0.8)"
    :round="30"
  >
    <view class="settings-box">
      <view class="settings-title">转发权限</view>
      <view
        class="settings-items ss-flex justify-between align-center border-b-f3"
        @click="changePower('all')"
      >
        <view class="settings-left">所有人</view>
        <view class="settings-right">
          <uni-icons
            type="checkmarkempty"
            size="30"
            color="#AAAAAA"
            v-show="state[state.powerType] === 'all'"
          ></uni-icons>
        </view>
      </view>
      <view
        class="settings-items ss-flex justify-between align-center border-b-f3"
        @click="changePower('friends')"
      >
        <view class="settings-left">仅互关好友</view>
        <view class="settings-right">
          <uni-icons
            type="checkmarkempty"
            size="30"
            color="#AAAAAA"
            v-show="state[state.powerType] === 'friends'"
          ></uni-icons>
        </view>
      </view>
      <view
        class="settings-items ss-flex justify-between align-center"
        @click="changePower('my')"
      >
        <view class="settings-left">仅自己</view>
        <view class="settings-right">
          <uni-icons
            type="checkmarkempty"
            size="30"
            color="#AAAAAA"
            v-show="state[state.powerType] === 'my'"
          ></uni-icons>
        </view>
      </view>
    </view>
  </su-popup>
</template>

<script setup>
import assNavbar from '@/components/ass-navbar.vue';
import sheep from '@/sheep';
import API from '../api';
import association from '@/association/store';
import {
  onLoad,
  onUnload
} from '@dcloudio/uni-app';
import {
  computed,
  reactive
} from 'vue';
import {
  reject
} from 'lodash';
import {
  platform
} from "../config"

const isAuditMode = computed(() => sheep.$store('app').isAuditMode);
const state = reactive({
  minHeight: 0, // 页面的最小高度
  videoDetails: null, // 选择的视频详情信息
  videoWidth: '', // 视频宽度
  videoHeight: '', // 视频高度
  videoBox: {
    // 视频盒子的组合宽高
    height: 0,
    width: 0,
  },
  title: '',
  videoPath: '',
  videoCover: '',
  tag_ids: [],
  friends: [],
  download: false,
  transpond: 'all',
  comment: 'all',
  settings_show: false, // 更多设置
  cart_show: false, // 带货
  power_show: false,
  powerType: '',
  throttle: false,
  goods: null,
  shop: null,
});
const theme = computed(() => association().theme);

onLoad((options) => {
  association().optionShow = false;
  console.log(association().optionShow);

  if (options) {
    // 解码
    options.path = decodeURIComponent(options.path);
    options.thumbTempFilePath = decodeURIComponent(options.thumbTempFilePath);
    options.width = Number(options.width);
    options.height = Number(options.height);
    options.duration = Math.ceil(options.duration);
    options.size = Number(options.size);
    state.videoDetails = options;
  }
  state.windowWidth = uni.getSystemInfoSync().windowWidth; //获取屏幕宽度
  state.minHeight =
    uni.getSystemInfoSync().windowHeight - (sheep.$platform.device.statusBarHeight + 44);
  state.videoWidth = (state.windowWidth - 50) / 2;
  state.videoHeight =
    ((state.windowWidth - 50) / 2) * (state.videoDetails.height / state.videoDetails.width);
  state.videoBox.width = (state.windowWidth - 50) / 2 + 'px';
  state.videoBox.height =
    ((state.windowWidth - 50) / 2) * (state.videoDetails.height / state.videoDetails.width) + 'px';

  // 监听 选择主题
  uni.$on('setMain', (res) => {
    state.tag_ids = res.list;
    let list = res.list.map((item) => {
      return `#${item}`;
    });
    state.title += list.join(' ');
  });

  // 监听 选择好友
  uni.$on('setFriend', (res) => {
    state.title += `@${res} `;
    state.friends.push(`@${res}`);
  });
  // 监听 选择商品
  uni.$on('select', (obj) => {
    state.goods = obj;
    state.shop = null;
  });
  uni.$on('select_shop', (obj) => {
    state.shop = obj;
    state.goods = null;
  });
});

onUnload(() => {
  uni.$off('setMain');
  uni.$off('setFriend');
  uni.$off('select');
  uni.$off('select_shop');
});

// 更换封面
const changeCover = () => {
  return
  // #ifdef MP-WEIXIN
  uni.chooseMedia({
    mediaType: ['image'],
    sourceType: ['album'],
    count: 1,
    success (res) {
      state.videoDetails.thumbTempFilePath = res.tempFiles[0].tempFilePath;
    },
  });
  // #endif

  // #ifdef APP
  uni.chooseImage({
    count: 1,
    sizeType: ['original'],
    success: (res) => {
      console.log('res:', res);
      state.videoDetails.thumbTempFilePath = res.tempFiles[0].path;
    },
  });
  // #endif
};

// 更换权限
const changePower = (type) => {
  state[state.powerType] = type;
  state.power_show = false;
};

const changePowerType = (type) => {
  state.powerType = type;
  state.settings_show = false;
  state.power_show = true;
};

const uploadVideo = () => {
  return new Promise(async (resolve, reject) => {
    const res = await API.upload(state.videoDetails.path);
    console.log('uploadVideo', res);
    if (res && res.url) {
      state.videoPath = res.url;
      // #ifndef MP-WEIXIN
      state.videoCover = res.url + '?ci-process=snapshot&time=0.01';
      // #endif
    }
    resolve();
  });
};

const uploadCover = () => {
  return new Promise(async (resolve, reject) => {
    const res = await API.upload(state.videoDetails?.thumbTempFilePath);
    console.log('uploadCover', res);
    if (res && res.url) {
      state.videoCover = res.url;
    }
    resolve();
  });
};

// 发布
const submit = async () => {
  if (state.title.length < 1) {
    uni.showToast({
      title: '请输入标题',
      icon: 'none',
      duration: 2000,
    });

    return
  }


  // if (state.throttle) {
  //   return;
  // }
  // state.throttle = true;
  uni.showLoading({
    title: '发布中',
    mask: true,
  });
  // 发布前将视频和封面的临时路径换成网络路径
  // #ifdef MP-WEIXIN
  const promises = [];
  if (!state.videoCover) {
    promises.push(uploadCover());
  }
  // #endif
  if (!state.videoPath) {
    promises.push(uploadVideo());
  }
  await Promise.all(promises).then(() => {
    API.addFind({
      category_id: state.videoDetails.id,
      title: state.title,
      content: '',
      cover: state.videoCover,
      file: state.videoPath,
      tag_ids: state.tag_ids.join(','),
      friends: state.friends.join(','),
      download: state.download ? '1' : '0',
      transpond: state.transpond,
      comment: state.comment,
      goods_promotion_id: state.goods ? state.goods.id : '',
      store_promotion_id: state.shop ? state.shop.id : '',
    }).then(res => {
      if (res.code == 1) {
        console.log(res, '请求');
        association().optionShow = true;
        uni.hideLoading();
        uni.showToast({
          icon: 'none',
          title: '发布成功',
          duration: 1000,
          success: () => {
            setTimeout(() => {
              sheep.$router.back();
              association().taBarId = true;
              uni.$emit('tabFun');
            }, 1500);
          },
        });
      }
    });
  });
};

function noneDo () {
  setTimeout(() => {
    uni.showToast({
      title: '功能暂未开发',
    });
  }, 100);
  return false;
}

const addMain = () => {
  sheep.$router.go('/association/pages/subject');
};

const addFriend = () => {
  sheep.$router.go('/association/pages/friend');
};

const changeSettingsPop = (e) => {
  state.settings_show = e.show;
};

const changeCartPop = (e) => {
  state.cart_show = e.show;
};

const changePowerPop = (e) => {
  state.power_show = e.show;
};
</script>


<style lang="scss" scoped>
@import '@/association/scss/index.scss';

view {
  box-sizing: border-box;
}

.content {
  background-color: #fff;
  padding: 20rpx 30rpx 0;
}

.describe {
  width: 686rpx;
  height: 270rpx;
  border-radius: 16rpx;
  background: #ffffff;
  border: 2rpx solid;
  padding: 20rpx;
  position: relative;

  textarea {
    width: 100%;
    height: 100%;
  }

  .describe-number {
    position: absolute;
    bottom: 10rpx;
    right: 30rpx;
    font-size: 20rpx;
    font-weight: normal;
    color: #aeaeae;

    text {
      color: #000000;
    }
  }
}

.carry {
  margin-top: 22rpx;

  .carry-item {
    width: 166rpx;
    height: 68rpx;
    border-radius: 16rpx;
    border: 2rpx solid;
    font-size: 28rpx;
    line-height: 68rpx;
    text-align: center;
    color: #666666;
    margin-right: 22rpx;
  }
}

.video-box {
  margin-top: 30rpx;

  .video {
    .video-duration {
      font-size: 28rpx;
      font-weight: normal;
      color: #666666;
      margin-top: 18rpx;
    }
  }

  .cover {
    .cover-image {
      width: 322rpx;
      height: 574rpx;
      border-radius: 16rpx;
    }

    .cover-text {
      font-size: 28rpx;
      font-weight: normal;
      color: #666666;
      margin-top: 18rpx;
    }
  }

  #video {
    width: 322rpx;
    height: 574rpx;
    border-radius: 16rpx;
  }
}

.settings {
  margin-top: 30rpx;

  .settings-item {
    height: 94rpx;
  }

  .settings-text {
    font-size: 32rpx;
    color: #666666;
    margin-left: 20rpx;
  }
}

.publish {
  margin-top: 120rpx;

  .publish-btn {
    width: 482rpx;
    height: 88rpx;
    border-radius: 20rpx;
    margin-bottom: 30rpx;

    .fabu {
      width: 40rpx;
      height: 40rpx;
      background: #ffffff;
      border-radius: 50%;
    }

    .publish-btn-text {
      font-size: 30rpx;
      color: #ffffff;
      margin-left: 15rpx;
    }
  }
}

.settings-box {
  width: 100%;
  // height: 726rpx;
  padding: 20rpx 38rpx 30rpx;

  .settings-title {
    font-size: 36rpx;
    color: #3d3d3d;
    text-align: center;
    margin-bottom: 20rpx;
  }

  .settings-items {
    height: 100rpx;

    .settings-left {
      font-size: 32rpx;
      color: #3d3d3d;
    }

    .settings-right {
      .right-text {
        color: #c4c4c4;
        font-size: 28rpx;
      }
    }
  }
}

.cart-box {
  width: 100%;
  height: 460rpx;
  padding: 46rpx 26rpx 0 34rpx;

  .cart-box-item {
    width: 100%;
    height: 94rpx;

    .cart-image {
      width: 40rpx;
      height: 40rpx;
      margin-right: 6rpx;
    }

    .cart-name {
      flex: 1;
      font-weight: 400;
      font-size: 32rpx;
      color: #3d3d3d;

      text {
        font-weight: 400;
        font-size: 22rpx;
        color: #989292;
      }
    }
  }
}

.border-b-f3 {
  border-bottom: 2rpx solid #f3f3f3;
}
</style>